<template>
  <div>
    <div>上传地址{{ imgUrl }}</div>
    <UploadImg v-model="imgUrl" />
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import UploadImg from '@/views/human/compuments/uploadimg.vue'
const cos = new COS({
  SecretId: 'AKID50f3AzYqqZ1C6j5C2cwzmHVTAajbCWZL',
  SecretKey: 'Yqrb5IEtGUR7WfX7QTFfolSs1tUpse9O'
})
export default {
  components: {
    UploadImg
  },

  data() {
    return {
      imgUrl: '',
      imageUrl: ''
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      console.log('beforeAvatarUpload', file)
      const isPng = file.type === 'image/png'
      if (!isPng) {
        this.$message.error('请上传image格式或png格式的图片')
      }
      return isPng
    },
    handleAvatarSuccess(res, file) {
      console.log(res, file)
    },
    httpRequest(res) {
      console.log('自定义上传', res)
      cos.putObject(
        {
          Bucket: 'hr77-1308949889' /* 必须 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须 */,
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          console.log(err || data)
          this.imageUrl = 'http://' + data.Location
        }
      )
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
